package com.example.rabbitmqdemo.hellorabbitmq.wrokqueues;


import com.example.rabbitmqdemo.hellorabbitmq.CommonUtil;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

@Slf4j
public class ConsumerWorkQueues {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = CommonUtil.getFactory();
        Connection connection = factory.newConnection();
        Thread thread1 = new Thread(new ConsumerThread(connection.createChannel(), "1"));
        Thread thread2 = new Thread(new ConsumerThread(connection.createChannel(), "2"));
        thread1.start();
        thread2.start();
    }


    static class ConsumerThread implements Runnable {
        private Channel channel;
        private String name;

        public ConsumerThread(Channel channel, String name) {
            this.channel = channel;
            this.name = name;
        }

        @Override
        public void run() {
            try {
                this.channel.basicConsume(ProducerWorkQueues.WORK_QUEUES, new DefaultConsumer(this.channel) {
                    @Override
                    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                        log.info("-- {} {}", name, new String(body));
                        Thread.yield();
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
